package com.example.elemboot.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.elemboot.Dao.IUser;
import com.example.elemboot.Entity.User;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Component
public class TokenUtils {
    private static IUser staticUserDao;
    @Resource
    IUser userDao;
    @PostConstruct
    public void setAdminService(){
        staticUserDao = userDao;
    }
    //生成token
    public static String createToken(String userPhone,String password){
        return JWT.create().withAudience(userPhone) //将userid保存到token里面作为载荷
                .withExpiresAt(DateUtils.addHours(new java.util.Date(), 2)) //过期时间
                .sign(Algorithm.HMAC256(password)); //密码作为密钥
    }
    //获取当前登录用户
    public static User getCurrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.isNoneBlank(token)){
                String userPhone = JWT.decode(token).getAudience().get(0);
                return staticUserDao.findUserByUserPhone(userPhone);
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }

}
